<?php
namespace control;
/*
*补卡申请类
*/

class workSignAddClass extends adIndexClass
{
    private const table = 'work_sign_add';
    private const page = 'workSignAdd';
    private const title = '补卡申请';
    private array $stateOption = ["草稿", "审核中", "已通过"];

    /*行政人事-补卡单-查询条件*/
    public function home()
    {
        $html = '';
        if ($this->power("workSignAdd", "seeAll")) {
            $html = selectMultiple(array("name" => "stid", "title" => L('clock.table.shen_qing_ren'), "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid'));
        }
        $html .=
            text(array('name' => 'orderNo', 'title' => L('clock.table.dan_ju_bian_hao'))) .
            text(array('name' => 'text', 'title' => L('clock.table.bu_ka_shi_you'))) .
            text(array('name' => 'deptName', 'title' => L('clock.table.sqrbm'))) .
            select(array("name" => "state", "title" => L('clock.table.zhuang_tai'), "option" => $this->stateOption)) .
            text(array("name" => "createTime", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('clock.table.bksjd') . "-" . L('clock.table.bksjd')));
        //返回
        return $this->homeFun($this->search($html));
    }


    /*行政人事-补卡单-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
            "state" => $this->post('state'),//办理状态（待处理/已完成）
        );
        $like = array(
            "deptName" => $this->post('deptName'),//申请人部门
            "text" => $this->post('text'),//补卡事由
        );
        //初始化
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'signTime');
        }
        //如果没有查看所有员工请假记录的权限
        if (!$this->power("workSignAdd", "seeAll")) {
            $and .= " and stid = '" . $this->control['stid'] . "' ";
        }
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        $page = $this->page(array("table" => "work_sign_add", "where" => $where, "order" => "signTime desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('clock.table.dan_ju_bian_hao'), L('clock.table.shen_qing_ren'), L('clock.table.bu_ka_shi_jian'), L('clock.table.bu_ka_shi_you'), L('clock.table.sqrbm'), L('clock.table.zhuang_tai'));
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //查询申请人
            $staff = query("staff", " stid = '$array[stid]' ");
            //单选框
            $dominate = array("box" => array("name" => "listId", "value" => $array['id']));
            $dominate['detail'] = array("title" => L('clock.table.bkxq'), "click" => "newIframe('" . L('clock.table.sign_info') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')");
            $text = zishu($array['text'], 88);
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'], $staff['name'], $array['signTime'], $text, $array['deptName'], $array['state']);
        }
        $button = "";
//		if($this->power("workSignAdd","edit")){
//			$button .= "<span class='spanButton'  onclick=\"newIframe(L('clock.table.gzrxq'),'" . $url . "&fun=edit')\">补卡申请</span>\n";
//		}
//		if($this->power("workSignAdd","del")){
//			$button .= "<span onclick=\"pasWarn('listForm','workSignAdd','delete')\" class='spanButton'>删除所选</span>\n";
//		}
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 审核通过后向签到记录中添加一条记录
     */
    public function insertSign($id)
    {
        $info = query('work_sign_add', " id = '$id'");
        $staff = query('staff', " stid = '$info[stid]'");
        insert(array(
            'table' => 'work_sign',
            'field' => $field = [
                'jobId' => $staff['jobId'],
                'stid' => $staff['stid'],
                'signTime' => $info['signTime'],
                'signId' => $info['id'],
                'type' => '补卡单'
            ]
        ));
        $workSignCheckClass = new workSignCheckClass();
        $workSignCheckClass->updatePersonalSign($staff, $field);//更新每日个人考勤数据
    }

    /**
     * 编辑
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: self::getId();
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    must . L('clock.table.bksjd') . "：" => text(array('name' => 'signTime', 'class' => 'text', 'laydate' => ['type' => 'datetime'], 'value' => $info['signTime'])),
                ],
                [
                    must . L('clock.table.bu_ka_shi_you') . "：" => textarea(array('name' => 'text', 'class' => 'textarea', 'value' => $info['text'])),
                ],
                [
                    L('clock.table.fileUpload') . "：" => fileUploadClass::addFileComponent($id, '补卡记录', self::page, self::page . 'EditForm')
                ],
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
            'button' => "<button class=\"button left-bottom\" onclick=\"subForm('{$this->get('cla')}EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')\">" . L('clock.table.commitBtn') . "</button>",
        ]);
        //返回
        return $this->tab($data);
    }

    /*编辑*/
    public function editEdit()
    {
        $id = $this->post('id');
        //赋值
        $field = array(
            "signTime" => $this->post('signTime'),
            "text" => $this->post('text'),//备注
        );
        $obj = new workSignCheckClass();
        //补卡时间的月份
        $month = date('Y-m', strtotime($field['signTime']));
        $endTime = $obj->lastMonthTime($month);
        if ($month == date('Y-m')) {
            $endTime = $this->time;
        }
        $idColloection = $this->staffCombination(true);
        //考勤规则
        $clockRule = query('clock_rule', " (concat(',',replace(selector,';',','),',') regexp concat(',',replace('{$idColloection}',',',',|,'),','))>0 and state = '启用' and UNIX_TIMESTAMP(startTime) <=UNIX_TIMESTAMP('{$endTime}') order by startTime desc");
        //当月已提交补卡的次数
        $commitNum = static::total(['table' => self::table, 'where' => "stid = '{$this->control['stid']}' and id !='$id'  and date_format(signTime,'%Y-%m') = '$month'"]);
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('clock.table.zxbz');
        } elseif (empty($field['signTime'])) {
            $json['warn'] = L('clock.table.qxzbksj');
        } elseif (empty($field['text'])) {
            $json['warn'] = L('clock.table.qtxbksy');
        } elseif (static::total(['table' => self::table, 'where' => " and signTime = '$field[signTime]' and stid = '{$this->control['stid']}' and id != '" . $this->post('id') . "' "]) > 0) {
            $json['warn'] = L('clock.table.nyzcsjdbksq');
        } elseif ($clockRule['id'] && $clockRule['maxNum'] != -1 && $commitNum >= $clockRule['maxNum']) {
            $json['warn'] = L('clock.table.sign_full');
        } elseif ($clockRule['id'] && $clockRule['maxDay'] != -1 && strtotime("-{$clockRule['maxDay']} day", strtotime($this->date)) > strtotime($field['signTime'])) {
            $json['warn'] = L('clock.table.ntjdbksjcclbksx');
        } else {
            if (empty($info['id'])) {
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'BKSQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ], $field);
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $field = array_merge($field, array("id" => $id, 'orderNo' => $userNo, 'state' => '草稿', 'deptName' => $department['name'], 'stid' => $this->control['stid'], "time" => date("Y-m-d H:i:s")));
                $json['warn'] = insert(array("table" => self::table, "field" => $field));
            } else {
                $userNo = $info['orderNo'];
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //添加主表ID到附件表
                $fileIdArr = $this->post('fileId');
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $text = str_replace(['{{staffName}}', '{{orderNo}}', '{{id}}'], [$this->control['name'], $userNo, $id], L('clock.table.sign_edit_text'));
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        return json_encode($json, 320);
    }


    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => L('clock.table.ti_jiao_shen_pi'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '补卡申请',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'prepare',
                            'data' => ['id' => $info['id']]
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => L('clock.table.tjspr'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('clock.table.zhuan_jiao'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('clock.table.shen_pi'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'finish',
                            'data' => ['id' => $info['id']]
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('clock.table.cxsp'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'cancelFun',
                            'data' => ['id' => $info['id']]
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /**
     * 撤销审批后的
     * @param $data
     */
    public function cancelFun($data)
    {
        $work_sign = query("work_sign", " signId = '$data[id]' ");
        $staff = query("staff", " stid = '$work_sign[stid]' ");
        //删除签到记录表中的补卡数据
        delete(array('table' => 'work_sign', 'where' => "signId = '$data[id]'"));
        $workSignCheckClass = new workSignCheckClass();
        $workSignCheckClass->updatePersonalSign($staff, $work_sign);//更新每日个人考勤数据
    }

    /*补卡详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = L('clock.table.no_sign_data');
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = L('clock.table.wzdcjl');
            } else {
                $data = array("id" => $info['id']);
                $button = [];
                if ($this->power(self::page, "edit") && $info['state'] == '草稿') {

                    //按钮
                    $button[] = [
                        "name" => L('clock.table.bian_ji'),
                        "type" => "顶部页卡",
                        "title" => L('clock.table.bian_ji'),
                        "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name" => L('clock.table.shan_chu'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }

                $audit = query('audit', " targetId = '$info[id]'");
                //审核按钮
                $button = array_merge($button, $this->auditButton($info));

                $data['html'] = $this->tableShow(array(
                    "button" => $button,
                    array(
                        array(
                            L('clock.table.bksjd') => $info['orderNo'],
                        ),
                        array(
                            L('clock.table.bu_ka_shi_you') => $info['text'],
                        ),
                    ),
                    L('clock.table.fu_jian') => array(
                        array(
                            fileUploadClass::showFile($info['id'], '补卡记录')
                        )
                    ),
                    L('clock.table.xi_tong_xin_xi') => array(
                        array(
                            L('clock.table.dan_ju_bian_hao') => $info['orderNo'],
                            L('clock.table.sqrbm') => $info['deptName'],
                            L('clock.table.shen_qing_ren') => self::findStaff($info['stid']),
                        ),
                        array(
                            L('clock.table.cjsj') => $info['time'],
                            L('clock.table.tjsj') => self::null($audit['commitTime']),
                            L('clock.table.zhuang_tai') => $info['state'],
                        ),
                    ),
                    L('clock.table.liu_cheng') => array(
                        array(
                            auditClass::auditRecord(self::table, $info['id'])
                        )
                    ),
                ));
                $html = $this->tab($data);
            }
        }
        return $html;
    }


    /**
     *
     * 提交审批前的验证
     */
    public function prepare($data): bool
    {
        $bool = true;
        $info = query(self::table, " id = '$data[id]'");
        //判断提交次数是否超过了考勤规则的次数
        //补卡时间的月份
        $month = date('Y-m', strtotime($info['signTime']));
        $obj = new workSignCheckClass();
        $endTime = $obj->lastMonthTime($month);
        if ($month == date('Y-m')) {
            $endTime = $this->time;
        }

        //根据员工选择器的值和当前员工的部门，职位，员工ID求交集
        $idColloection = $this->staffCombination(true);
        //考勤规则
        $clockRule = query('clock_rule', " (concat(',',replace(selector,';',','),',') regexp concat(',',replace('{$idColloection}',',',',|,'),','))>0 and state = '启用' and UNIX_TIMESTAMP(startTime) <=UNIX_TIMESTAMP('{$endTime}') order by startTime desc");
        //当月已提交补卡的次数
        $commitNum = static::total(['table' => self::table, 'where' => " and stid = '{$this->control['stid']}' and state !='草稿' and date_format('{$info['signTime']}','%Y-%m') = '$month'"]);
        if ($clockRule['id'] && $clockRule['maxNum'] != -1 && $commitNum >= $clockRule['maxNum']) {
            $bool = L('clock.table.sign_full');
        }
        return $bool;
    }

    /**
     * 审批结束后需要执行的操作
     * @param $data
     */
    public function finish($data)
    {

        $this->insertSign($data['id']);//向签到记录表中插入一条数据
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('clock.table.sign_del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /*行政人事-补卡单-删除自己的补卡单*/
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('clock.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('clock.table.nygsjdmzxzn');
        } else {
            $log = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                //查询
                $workSignAdd = query("work_sign_add", " id = '$id' ");
                //判断
                if (!$this->power(self::page,'seeAll') && $workSignAdd['stid'] != $this->control['stid']) {
                    $log .= str_replace(['{{orderNo}}'], [$workSignAdd['orderNo']], L('clock.table.sign_del_warn'));
                } elseif ($workSignAdd['state'] != "草稿") {
                    $log .= str_replace(['{{orderNo}}'], [$workSignAdd['orderNo']], L('clock.table.sign_del_warn_two'));
                } else {
                    delete(array("table" => "audit", "where" => " targetId = '$id' "));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //删除补卡单
                    delete(array("table" => "work_sign_add", "where" => " id = '$id' "));
                    //日志
                    $log .= str_replace(['{{orderNo}}'], [$workSignAdd['orderNo']], L('clock.table.sign_del_warn_three')) . "<br>";

                    $x++;
                }
            }
            //返回信息
            $text = str_replace('{{staffName}}', $this->control['name'], L('clock.table.sign_del_text')) . "<br>" . $log;
            $this->logText(array("type" => "workSignAdd", "text" => $text));
            $_SESSION['warn'] = str_replace('{{x}}', $x, L('clock.table.sign_del_tip'));
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home';
        }
        return json_encode($json, 320);
    }
}
